<template>
  <div>
    <el-button type="primary"
               @click="addSecondCategory">添加二级分类</el-button>
    <el-table :data="categoryData"
              row-key="id"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column :prop="index"
                       :label="item"
                       v-for="(item, index)
                       in
                       tableColumList"
                       :key="index">

        <template slot-scope="scope">
          <div v-if="item == `状态`">
            <el-tag v-if="scope.row.status == 1"
                    size="medium"> 有效</el-tag>
            <el-tag v-else
                    size="danger">无效 </el-tag>
          </div>
          <div v-else-if="item == `图片`">
            <el-image :src="scope.row.iconUrl"
                      style="width:38 px; height : 38px">
              <div slot="error"
                   class="image-slot">
                <i> 暂无图片</i>
              </div>
            </el-image>
          </div>

          <div v-else-if="item == `操作`"
               style="display: inline-block">
            <el-button v-if="scope.row.level ==2 "
                       type="primary"
                       icon="el-icon-plus"
                       circle
                       @click="addThirdCategory(scope.row)"></el-button>
            <el-button type="primary"
                       icon="el-icon-edit"
                       @click="editCategory(scope.row)"
                       circle> </el-button>
            <el-button type="danger"
                       icon="el-icon-delete"
                       circle
                       @click="deleteCategory(scope.row)">
            </el-button>
          </div>
          <div v-else-if="item == `显示主页`">
            <el-tag v-if="scope.row.isHome == 1"
                    size="medium"> 显示</el-tag>
            <el-tag v-else
                    size="danger">不显示 </el-tag>
          </div>

          <div v-else>
            {{scope.row[index]}}
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="添加二级分类"
               :visible.sync="dialogVisibleAddSecondCategory">

      <el-form :model="secondCateoryForm"
               label-width="80px"
               ref="secondCateoryForm"
               :rules="rules">
        <el-form-item label="分类名称"
                      prop="name">
          <el-input v-model="secondCateoryForm.name"></el-input>
        </el-form-item>

        <el-form-item label="等级"
                      prop="level">
          <el-input type="number"
                    v-model="secondCateoryForm.level"
                    placeholder="等级必须为2"></el-input>
        </el-form-item>
        <el-form-item label="父类别"
                      prop="parentId">
          <el-select v-model="secondCateoryForm.parentId"
                     placeholder="请选择父类别">
            <el-option v-for="item in secondCategorySelectList"
                       :key="item.index"
                       :value="item.id"
                       :label="item.name"></el-option>

          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="onSubmitSecondCategory('secondCateoryForm')">提交</el-button>
          <el-button type="primary"
                     @click="closeDialog('secondCateoryForm')">取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <el-dialog title="添加三级分类"
               :visible.sync="dialogVisibleAddThirdCategory">
      <el-form :model="addThirdCategoryForm"
               ref="addThirdCategoryForm"
               :rules="rules"
               label-width="80px">
        <el-form-item label="父分类名称">
          <el-input v-model="addThirdCategoryForm.parentName"
                    disabled
                    placeholder=""></el-input>
        </el-form-item>

        <el-form-item label="父分类id"
                      v-show="false">
          <el-input v-model="addThirdCategoryForm.parentId"
                    placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="分类名称"
                      prop="name">
          <el-input v-model="addThirdCategoryForm.name"
                    placeholder="输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="等级"
                      prop="level">
          <el-input v-model="addThirdCategoryForm.level"
                    placeholder="等级必须为3"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-upload ref="upload"
                     action
                     list-type="picture-card"
                     :limit="1"
                     :show-file-list="true"
                     :auto-upload="false"
                     :on-change="change"
                     :on-exceed="exceed">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="onSubmitThirdCategory('addThirdCategoryForm')">提交</el-button>
          <el-button type="primary"
                     @click="closeDialog('addThirdCategoryForm')">取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <!-- 修改弹窗 -->

    <el-dialog title="修改分类"
               :visible.sync="editCategoryDialogVisible">
      <el-form :model="editForm"
               ref="editForm"
               :rules="rules"
               label-width="80px">
        <el-form-item label="编号">
          <el-input v-model="editForm.id"
                    disabled></el-input>
        </el-form-item>
        <el-form-item label="分类名称"
                      prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="主页显示"
                      v-if="editForm.level == 1"
                      prop="isHome">
          <el-switch v-model="editForm.isHome"
                     active-color="#13ce66"
                     inactive-color="#ff4949"
                     :active-value="1"
                     :inactive-value="0">

          </el-switch>
        </el-form-item>

        <el-form-item label="图标"
                      v-if="editForm.level != 2 ">
          <el-upload ref="upload"
                     action
                     :accept="'.png'"
                     list-type="picture-card"
                     :limit="1"
                     :show-file-list="true"
                     :auto-upload="false"
                     :file-list="editFileList"
                     :on-change="editChange"
                     :on-exceed="exceed">
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="onSubmitEditCategory('editForm')">提交</el-button></el-button>
          <el-button type="primary"
                     @click="closeDialog('editForm')">取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "CategorySetting",
  components: {},
  data() {
    return {
      categoryData: [],
      tableColumList: {
        id: "编号",
        name: "分类名称",
        iconUrl: "图片",
        level: "等级",
        status: "状态",
        isHome: "显示主页",
        tool: "操作",
      },
      //添加二级分类弹窗
      dialogVisibleAddSecondCategory: false,
      // 添加三级分类弹窗
      dialogVisibleAddThirdCategory: false,
      // 修改分类弹窗显示控制
      editCategoryDialogVisible: false,
      //添加二级分类数据
      secondCateoryForm: {
        name: "",
        level: "",
        parentId: ""
      },
      addThirdCategoryForm: {
        parentId: "",
        name: "",
        level: "",
        parentName: ""
      },
      //二级分类select 下拉数据
      secondCategorySelectList: [],
      //添加三级分类的图片
      addImageFileArry: [],

      // 修改分类 回显图片 
      editFileList: [],
      //修改分类图片
      editFileArray: [],
      editForm: {
        name: "",
        level: "",
        id: "",
        iconUrl: "",
        isHome: ""
      },
      isChangeIcon: false,

      headers: {
        "Content-Type": "multipart/form-data",
      },
      //共用一个rules
      rules: {
        name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
        ],
        level: [{ required: true, message: "等级不能为空", trigger: "blur" }],
        parentId: [{ required: true, message: "父类别不能为空", trigger: "blur" }],
        isHome: [{ required: true, message: "主页显示不能为空", trigger: "blur" }]
      },
    };
  },

  methods: {
    // 获取分类列表
    getCategoryList() {
      this.getRequest("/category/api/getAllCategory").then((res) => {
        //  console.log(res);
        if (res.code == 200 && res.msg == "success") {
          this.categoryData = res.data;
          this.totalNum = res.total;
        } else {
          this.$$confirm("错误了", "提示", {
            confirmButtonText: "确定",

          });
        }
      });
    },

    //添加二级分类
    addSecondCategory() {
      // 加载 select 下拉框数据
      this.getRequest("/category/api/getAllFirstCategory").then((res) => {
        console.log("下拉框", res);
        if (res.code == 200 && res.msg == "success") {
          this.secondCategorySelectList = res.data;

        } else {
          this.$$confirm("错误了", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消"
          });
        }
      });

      this.dialogVisibleAddSecondCategory = true;
    },
    // 取消 关闭添加二级分类弹窗
    closeEditDialog(formName) {
      this.dialogVisibleAddSecondCategory = false;
    },

    //提交添加二级类别
    onSubmitSecondCategory(formName) {
      console.log("提交添加二级类别", this.secondCateoryForm);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.postRequest("/category/api/addSecondCategory", this.secondCateoryForm).then((res) => {
            // console.log(res);
            if (res.code == 200 && res.msg == "success") {
              this.$confirm("添加成功", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消"
              });
              // 关闭弹窗
              this.dialogVisibleAddSecondCategory = false;
              this.closeDialog(formName);
              // 刷新表格
              this.getCategoryList();
            } else {
              this.$alert(res.msg, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消"
              }
              );
            }

          })
        }
      })

    },
    // 删除分类
    deleteCategory(row) {
      if (row.children.length > 0) {
        this.$confirm("请先删除子分类", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        })
      } else if (row.children.length <= 0) {
        this.$confirm("此操作将永久删除该分类，是否继续", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.deleteRequest("/category/api/deleteCategory/" + row.id).then((res) => {
            if (res.code == 200 && res.msg == "success") {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getCategoryList();
            } else {
              this.$message({
                type: 'error',
                message: '删除失败!'
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });

        })
      }

    },


    //修改分类
    editCategory(row) {
      console.log("edit")
      this.getRequest("/category/api/getCategoryById/" + row.id).then((res) => {
        if (res.code == 200 && res.msg == "success") {
          this.editForm = res.data;
          // 回显图片
          this.editFileList = [{ name: res.data.name, url: res.data.iconUrl }];
          this.editCategoryDialogVisible = true;
        } else {
          this.$message.error(res.msg);
        }
      })
    },

    //提交修改分类接口
    onSubmitEditCategory(formName) {
      let params = new FormData();
      params.append("id", this.editForm.id);
      params.append("name", this.editForm.name);
      if (this.isChangeIcon == true) {
        console.log(this.editFileArray[0])
        params.append("file", this.editFileArray[0]);
      }
      params.append("isChangeIcon", this.isChangeIcon);
      params.append("isHome", this.editForm.isHome);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.uploadRequest("/category/api/update", params, this.headers).then(
            (res) => {
              if (res.code == 200 && res.msg == "success") {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                this.editCategoryDialogVisible = false;
                this.isChangeIcon = false;
                //清空表单
                this.closeDialog(formName);
                // 刷新表格
                this.getCategoryList();
              } else {
                this.$message({
                  type: 'error',
                  message: '修改失败!'
                });
              }
            }
          )
        }
      })


    },


    //打开添加三级列表的弹窗
    addThirdCategory(row) {
      console.log(row);
      this.addThirdCategoryForm.parentId = row.id;
      this.addThirdCategoryForm.parentName = row.name;
      this.dialogVisibleAddThirdCategory = true;

    },
    // 三级列表上传的接口
    onSubmitThirdCategory(formName) {
      let params = new FormData();
      params.append("parentId", this.addThirdCategoryForm.parentId);
      params.append("name", this.addThirdCategoryForm.name);
      params.append("level", this.addThirdCategoryForm.level);
      params.append("file", this.addImageFileArry[0]);

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.uploadRequest("/category/api/addThirdCategory", params, this.headers).then((res) => {
            console.log(res);
            if (res.code == 200 && res.msg == "success") {
              // 关闭弹窗
              this.$message({
                type: 'success',
                message: '添加成功!'
              });
              this.dialogVisibleAddThirdCategory = false;
              this.$refs.upload.clearFiles();
              // 清空表单数据
              this.closeDialog(formName);
              // 刷新表格
              this.getCategoryList();
            } else {
              this.$alert(res.msg, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消"
              });
            }

          })
        }
      })
    },


    // closeDialogSecond(formName) {
    //   this.$refs[formName].resetFields();
    //   this.dialogVisibleAddSecondCategory = false;

    // },
    // 共用 一个 closeDialog 方法  清空表单 清空 文件 关闭弹窗
    closeDialog(formName) {
      if (formName == "addThirdCategoryForm") {
        //添加三级分类 的图片数组
        this.addImageFileArry = [];
        this.$refs[formName].resetFields();
        this.$refs.upload.clearFiles();
        // 关闭三级分类弹窗
        this.dialogVisibleAddThirdCategory = false;
      } else if (formName == "editForm") {
        // 修改分类的图片数组
        this.editFileArray = [];
        // 回显数据的图片数组
        this.editFileList = [];
        this.$refs[formName].resetFields();
        this.$refs.upload.clearFiles();
        // 关闭编辑分类弹窗
        this.editCategoryDialogVisible = false;
      } else if (formName == "secondCateoryForm") {
        //关闭添加二级分类弹窗
         this.$refs[formName].resetFields();
        this.dialogVisibleAddSecondCategory = false;
      }



    },

    // 上传图片钩子函数
    // 上传和编辑使用同一个exceed方法限制上传一张图片
    exceed() {
      this.$message.warning(`当前限制选择 1个文件`);
    },
    change(file, fileList) {
      if (fileList.length > 0) {
        this.addImageFileArry.push(file.raw);
      }
    },

    editChange(file, fileList) {
      this.isChangeIcon = true;
      if (fileList.length > 0) {
        this.editFileArray.push(file.raw);
      }
    },

  },

  created() {
  },
  // 钩子函数获取数据
  mounted() {
    // 加载table 
    this.getCategoryList();

  },
};
</script>

<style lang="css">
</style>
